from pygame import font
from helpers import * #@UnusedWildImport
from Level import Level
from Camera import Camera
from TileCache import TileCache
from Sprite import * #@UnusedWildImport
from Interface import Interface

class Edit(object):

    def __init__(self):
        self.screen = pygame.display.get_surface()
        self.spriteCache = TileCache()
        self.tileCache = TileCache(32,32)
        self.sprites = SortedUpdates()
        self.camera = Camera()
        pygame.font.init()
        self.text = pygame.font.Font(None, 32)
        self.interface = Interface()
        self.file = Input(x = 50, y = 250, maxlength=40, color=(0,0,0), prompt='filename: ')
        self.state = "OPTIONS_MENU"
        self.lmouse = True
        self.rmouse = True
        
    def update(self):
        pass
    
    def handleEvents(self):
        events = pygame.event.get()
        for event in events:
            if self.state is "OPTIONS_MENU":
                if event.type == QUIT:
                    return False
                elif event.type == KEYDOWN:
                    if event.key == K_ESCAPE:
                        return False
            else:
                if event.type == QUIT:
                    self.state = "OPTIONS_MENU"
                elif event.type == KEYDOWN:
                    if event.key == K_ESCAPE:
                        self.state = "OPTIONS_MENU"
                elif event.type == MOUSEBUTTONDOWN and self.state is "EDITING_MAP":
                    if event.button == 1:
                        self.tilestart = self.tilecoord()
                    elif event.button == 3:
                        self.mouseclick("right")
                elif event.type== MOUSEBUTTONUP and self.state is "EDITING_MAP":
                    if event.button == 1:
                        self.mouseclick("left")

        if self.state is "EDITING_MAP":
            if self.keyIsDown(K_LCTRL) and self.keyIsDown(K_s):
                self.state = "SAVE_OPTION"
            x, y, w, h = self.camera.get_bounds()
            if self.keyIsDown(K_RIGHT) and (x+w+5) <= (self.level.width * MAP_TILE_WIDTH):
                self.camera.move_x(5)
            elif self.keyIsDown(K_LEFT) and (x) >= 5:
                self.camera.move_x(-5)
            if self.keyIsDown(K_UP) and y >= 5:
                self.camera.move_y(-5)
            elif self.keyIsDown(K_DOWN) and (y+h+5) <= (self.level.height * MAP_TILE_HEIGHT):
                self.camera.move_y(5)       
            return True
        elif self.state is "LOAD_OPTION":
            self.file.update(events)
            levelname = self.file.check()
            if len(levelname) > 1:
                self.loadLevel(Level(levelname))
                self.state = "EDITING_MAP"
        elif self.state is "SAVE_OPTION":
            self.file.update(events)
            levelname = self.file.check()
            if len(levelname) > 1:
                self.level.saveLevel(levelname)
                self.state = "EDITING_MAP"
        elif self.state is "OPTIONS_MENU":
            if self.keyIsDown(K_LCTRL) and self.keyIsDown(K_o):
                self.state = "LOAD_OPTION"
            elif self.keyIsDown(K_LCTRL) and self.keyIsDown(K_s):
                self.state = "SAVE_OPTION"
    
    def keyIsDown(self, key):
        keystate=pygame.key.get_pressed()
        if keystate[key]:
            return True
        return False
    
    def tilecoord(self):
        x, y = pygame.mouse.get_pos()
        camx, camy = self.camera.get_coords()
        x += camx
        y += camy
        x /= MAP_TILE_WIDTH
        y /= MAP_TILE_HEIGHT
        return (x, y)
            
    def mouseclick(self, button="left"):
        if button is "left":
            x, y = self.tilecoord()
            dx, dy = self.tilestart
            if x < dx:
                q = x
            else: 
                q = dx
            if y < dy:
                r = y
            else:
                r = dy
            for a in range(abs(x - dx) + 1):
                for b in range(abs(y - dy) + 1):
                    self.level.swap_tile(a+q, b+r)
        elif button is "right":
            x, y = self.tilecoord()
            print self.level.get_name(x, y)
            
            if self.level.get_name(x, y) == "u_left_corner":
                self.level.swap_tile(x, y, "b_left_corner")
            elif self.level.get_name(x, y) == "b_left_corner":
                self.level.swap_tile(x, y, "b_right_corner")
            elif self.level.get_name(x, y) == "b_right_corner":
                self.level.swap_tile(x, y, "u_right_corner")
            elif self.level.get_name(x, y) == "u_right_corner":
                self.level.swap_tile(x, y, "u_left_corner")
            elif self.level.get_name(x, y) == "u_side":
                self.level.swap_tile(x, y, "left_side")
            elif self.level.get_name(x, y) == "left_side":
                self.level.swap_tile(x, y, "b_side")
            elif self.level.get_name(x, y) == "b_side":
                self.level.swap_tile(x, y, "right_side")
            elif self.level.get_name(x, y) == "right_side":
                self.level.swap_tile(x, y, "u_side")
            elif self.level.get_name(x, y) == "u_left_inside":
                self.level.swap_tile(x, y, "b_left_inside")
            elif self.level.get_name(x, y) == "b_left_inside":
                self.level.swap_tile(x, y, "b_right_inside")
            elif self.level.get_name(x, y) == "b_right_inside":
                self.level.swap_tile(x, y, "u_right_inside")
            elif self.level.get_name(x, y) == "u_right_inside":
                self.level.swap_tile(x, y, "u_left_inside")
        self.loadLevel(self.level)
        
    def display(self):
        self.screen.fill((255,255,255))
        if self.state is "EDITING_MAP":
            x , y, w, h = self.camera.get_bounds()
            for i in range (w / 2 / MAP_TILE_WIDTH + 1):
                for j in range (h / MAP_TILE_HEIGHT / 2 + 2):
                    self.screen.blit(self.background, (i*2*MAP_TILE_WIDTH - (x%(MAP_TILE_WIDTH*4))/2, j*2*MAP_TILE_HEIGHT - (y%(MAP_TILE_HEIGHT*4)/2)))        
            self.screen.blit(self.terrain, (-x, -y))
        elif self.state is "OPTIONS_MENU":         
            text = "Ctrl+N - New Map"
            self.screen.blit(self.text.render(text, 1, (0,0,0)), (230, 100))
            text = "Ctrl+O - Open Map"
            self.screen.blit(self.text.render(text, 1, (0,0,0)), (225, 150))
            text = "Ctrl+S - Save Map"
            self.screen.blit(self.text.render(text, 1, (0,0,0)), (230, 200))
        elif self.state is "LOAD_OPTION" or self.state is "SAVE_OPTION":
            self.file.draw(self.screen)
        
        self.interface.CorneredBox(self.screen, 0, 480, 640, 160)
        
    def loadLevel(self, level):
        self.sprites = SortedUpdates()
        self.overlays = pygame.sprite.RenderUpdates()
        self.level = level
        for pos, tile in level.items.iteritems():
            sprite = Sprite(pos, self.spriteCache[tile["sprite"]])
            
            self.sprites.add(sprite)
            
            self.terrain, overlays, self.background = self.level.render()
            for (x, y), image in overlays.iteritems():
                overlay = pygame.sprite.Sprite(self.overlays)
                overlay.image = image
                overlay.rect = image.get_rect().move(x*MAP_TILE_WIDTH, y*MAP_TILE_HEIGHT - MAP_TILE_HEIGHT)
        self.terrain, overlays, self.background = self.level.render()
        self.map_is_loaded=True